<?php
require_once("lib/renren/config.inc.php");
require_once(ROOT_DIR."/dao/user_dao.php");
require_once("lib/renren/RenRenClient.class.php");
class LRenRen {
	static public function getAuthUrl($callback){
		global $config;
		$_SESSION["redirect_uri"] = $callback;	// 之后用code获取access token时参数redirect_uri要与这个一样，所以保存进session里
		$url = $config->auth_url."?client_id={$config->APIKey}&response_type=code&scope=publish_share&redirect_uri=".urlencode($callback);
		return $url;
	}
	
	static public function connect(&$user_id, $code){
		global $config;
		$rrObj = new RenRenClient();
		$param = array(
			"grant_type"=>"authorization_code",
			"code"=>$code,
			"client_id"=>$config->APIKey,
			"client_secret"=>$config->SecretKey,
			"redirect_uri"=>$_SESSION['redirect_uri']
		);
		// 用code获取access_token
		$token = $rrObj->_POST($config->oauth_token_url, $param);

		// 获取用户session key
		$return_obj = new stdClass;
		$session_key = self::_getSessionKey($token->access_token, $token->refresh_token, $return_obj);

		$rrObj->setSessionKey($session_key);
		
		// 获取资料
		$userInfo = $rrObj->POST('users.getProfileInfo', array($return_obj->user->id,'uid,name,friends_count,visitors_count'));
		if($userInfo->error_code){
			die($userInfo->error_msg);
		}
		// 判断该用户是否存在
		$renren_id = $userInfo->uid;
		$sql = "select * from sync_renren where renren_id={$renren_id}";
		$row = DB::getRow($sql);
		if($row){
			// 有了，更新token
			if($user_id){
				// 合并同步
				DB::query("update sync_renren set user_id={$user_id} where renren_id={$renren_id}");
				// 修改该记录的user_id为合并合的ID
				DB::query("update user set renren=1 where user_id={$user_id}");
				// 删除原来那条同步记录
				DB::query("delete user where user_id={$row['user_id']}");
			}else{
				$user_id = $row['user_id'];
			}
			$sql = "update sync_renren set friends={$userInfo->friends_count},views={$userInfo->visitors_count},access_token='{$token->access_token}'"
					.",refresh_token='{$token->refresh_token}',expires_in={$token->expires_in} where renren_id={$renren_id}";
			$ret = DB::query($sql);
			return DB::getRow("select * from sync_renren where renren_id={$renren_id}");
		}else{
			if($user_id){
				// 已同步到其它平台，修改人人的同步位即可
				$sql = "update user set renren=1 where user_id={$user_id}";
				DB::query($sql);
			}else{
				// 新用户，保存, 新同步记录
				$sql = "insert into user(renren) values(1)";
				$ret = DB::query($sql);
				$user_id = DB::newInsertId();
			}
			// 人人表里加记录
			$sql = "insert into sync_renren(user_id,friends,views,renren_id,name,access_token,refresh_token,expires_in) "
					." values({$user_id},{$userInfo->friends_count},{$userInfo->visitors_count},{$renren_id},'{$userInfo->name}',"
					."'{$token->access_token}','{$token->refresh_token}',{$token->expires_in})";
			$ret = DB::query($sql);
			$ret = DB::getRow("select * from sync_renren where user_id={$user_id}");
			return $ret;
		}
	}
	
	static public function publish($user_id, $url, $msg){
		// 根据user_id，从数据库获取token
		$userDao = new UserDao();
		$token_info = $userDao->getRenRenTokenInfo($user_id);
		// 用token去获取session key
		$obj = new RenRenClient();
		$return_obj = new stdClass;
		$session_key = self::_getSessionKey($token_info['access_token'], $token_info['refresh_token'], $return_obj);
var_dump($return_obj);
		$obj->setSessionKey($session_key);
		// 发布共享
		// 分享的类型：日志为1、照片为2、链接为6、相册为8、视频为10、音频为11 
		$result = $obj->POST('share.publish', array(6, $url, $msg));
var_dump($result);
		if($result->result && $result->result==1){
			return true;
		}else{
			exit();
		}
	}
	
	/**
	 * 返回session key 
	 * return_obj的格式
	 * {
		    "renren_token": {
		        "expires_in": 81645,
		        "session_secret": "4671832de71c2032384bc2762fbd7c25",
		        "session_key": "5.a6b7dbd428f731035f771b8d15063f61.86400.1292922000-222209506"
		    },
		    "oauth_token": "10000|5.a6b7dbd428f731035f771b8d15063f61.86400.1292922000-222209506",
		    "user": {
		        "id": 222209506
		    }
		}
	 */
	static private function _getSessionKey($access_token, $refresh_token, &$return_obj){
		global $config;

		$obj = new RenRenClient();
		// 获取用户session key
		$param = array("oauth_token"=>$access_token);
		$session = $obj->_POST($config->session_key_url, $param);
		if(isset($session->error)){
			if("expired_token" == $session->error){
				// token 过期
				$token = self::_refreshToken($refresh_token);
				return $this->_getSessionKey($token->access_token, $token->refresh_token, $return_obj);
			}else{
				die($session->error."<br>".$session->error_description);
			}
		}
		$return_obj = $session;
		return $session->renren_token->session_key;
//		$session_key = $session->renren_token->session_key;
//		$obj->setSessionKey($session_key);
	}
	
	/**
	 *	返回格式 {
		    "access_token": "10000|5.a6b7dbd428f731035f771b8d15063f61.86400.1292922000-222209506",
		    "expires_in": 87063,
		    "refresh_token": "10000|5.385d55f8615fdfd9edb7c4b5ebdc3e39.604800.1293440400-222209506",
		    "scope": "publish_feed email"
		}
	 */
	static private function _refreshToken($refresh_token){
		global $config;
		$obj = new RenRenClient();
		$param = array(
			'grant_type' => 'refresh_token',
			'refresh_token' => $refresh_token,
			'client_id'=>$config->APIKey,
			'client_secret'=>$config->SecretKey
		);
		$token = $obj->_POST($config->oauth_token_url, $param);
		if($token->error){
			die($token->error." : ".$token->error_description);
		}
		return $token;
	}
}